/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentPage;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.service.core.LayoutManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentPageForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Prepares form bean to update content page's data
 * </p>
 * <p><a href="CallUpdateContentPageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.26 $ $Date: 2008/04/29 17:48:06 $
 * @struts.action path="/core/contentPage/callUpdate"
 * name="contentPageForm"
 * scope="request"
 * validate="false"
 * roles="core-contentPage-update, core-contentPage-view"
 * @struts.action-forward name="updateContentPage"
 * path=".core.contentPage.update"
 * @struts.action-forward name="listContentPages"
 * path="/core/contentPage/list.do"
 * redirect="true"
 */
public final class CallUpdateContentPageAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        // Check whether it's normal edit (from list of content pages) or
		// it was invoked from context menu
		String redirectUrl = request.getParameter("redirectUrl");
        if ( !GenericValidator.isBlankOrNull(redirectUrl) ) {
			// It was invoked from context menu
			session.setAttribute(WebappConstants.REDIRECT_URL_KEY, redirectUrl);
		}

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);

        if ( isCancelled(request) ) {
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentPages");
		}

        if (!request.isUserInRole("core-contentPage-update")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
        }

		ContentPageForm contentPageForm = (ContentPageForm) form;
		Long contentPageId;
        if ( contentPageForm.getId() != null ) {
			contentPageId = Long.valueOf(contentPageForm.getId());
		} else if ( session.getAttribute(WebappConstants.CONTENT_PAGE_ID_KEY) != null ) {
			contentPageId = (Long) session.getAttribute(WebappConstants.CONTENT_PAGE_ID_KEY);
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content page ID. Returning to list...");
			}
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentPages");
		}

		PageManager contentPageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
		ContentPage contentPage = contentPageManager.retrieveContentPage(contentPageId);
		if ( contentPage == null ) {
			// content page not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("contentPageNotFound", new ActionMessage("core.contentPage.errors.notFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentPages");
		}
		WebappUtil.copyProperties(contentPageForm, contentPage, request);
		contentPageForm.setLayoutId(String.valueOf(contentPage.getLayout().getId()));
		contentPageForm.setTitleMap(contentPage.getTitle());
		contentPageForm.setDescriptionMap(contentPage.getDescription());
		contentPageForm.setKeywordsMap(contentPage.getKeywords());

		String uri = contentPage.getUri();
		if ( uri.startsWith(WebappConstants.CONTENT_PAGES_URI_PREFIX) ) {
			uri = uri.substring(WebappConstants.CONTENT_PAGES_URI_PREFIX.length());
		}
		contentPageForm.setUri(uri);

		// Populate layout drop-down list
		LayoutManager layoutManager = (LayoutManager) getBean(Constants.LAYOUT_MANAGER_BEAN);
		PartialCollection layouts = layoutManager.listLayouts(null);

		if ( layouts != null ) {
			for ( Iterator i = layouts.iterator(); i.hasNext(); ) {
				Layout layout = (Layout) i.next();
				if ( layout.getCpDefinition() == null || layout.getCpDefinition().length() == 0 ) {
					i.remove();
				}
			}
		}

		if ( layouts == null || layouts.size() == 0 ) {
			saveToken(request);
			ActionMessages errors = new ActionMessages();
			errors.add("noLayoutFound", new ActionMessage("core.contentPage.errors.noLayoutFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentPages");
		}

		session.setAttribute(WebappConstants.LAYOUT_COLLECTION_KEY, layouts);

		List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();

		session.setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("updateContentPage");
	}

}